#include <LitStdAfx.h>
#include <LitFilePath.h>
#include <LitFileSystem.h>

namespace Lit
{
	FilePath::FilePath( ){}
	FilePath::FilePath( const char* path ){ p=path; sanitise(); }
	FilePath::FilePath( const std::string &path ){ p=path; sanitise(); }
	FilePath::FilePath( const FilePath& path ){ p = path.p; sanitise(); }
	FilePath::~FilePath(){}
		
	bool FilePath::startsWith( const FilePath & path ) const
	{
		return Ogre::StringUtil::startsWith( p, path.str(), true );
	}
	bool FilePath::endsWith( const FilePath & path ) const
	{
		return Ogre::StringUtil::endsWith( p, path.str(), true );
	}
	bool FilePath::contains( const FilePath & path ) const
	{
		std::string lp; for( auto i=p.begin(); i!=p.end(); i++ ) lp.push_back( std::tolower(*i) );
		std::string lp2; for( auto i=path.str().begin(); i!=path.str().end(); i++ ) lp2.push_back( std::tolower(*i) );

		return (p.find(path.str())!=std::string::npos);
	}
	std::string FilePath::removeIfFound( const FilePath & rem_path ) const
	{
		size_t count = rem_path.str().size();
		size_t pos = p.find(rem_path.str());
		if( pos!=std::string::npos )
		{
			return p.substr( (pos+1), count-(pos+1) );
		}
		return p;
	}
	std::string FilePath::extension() const{ 
		std::string fname(fileName());
		size_t p = fname.find_last_of('.');
		if( p == std::string::npos )
			return "";
		return fname.substr( p+1, fname.size() - (p+1) );
	};
	std::string FilePath::fileName( bool with_ext ) const{ 
		std::string n = Lit::FileSystem::fileName(p); 
		
		if( with_ext ) return n;

		size_t pos = n.find_last_of('.');
		if( pos == std::string::npos ) return n;
		n = n.substr(0, pos);
		return n;
	}
	std::string FilePath::dirName() const{ return Lit::FileSystem::dirName(p); }
	
	LIT_API std::ostream& operator<<( std::ostream& strm, const FilePath& p )
	{
		strm << p.p;
		return strm;
	}

	FilePath FilePath::parent() const{ return FilePath(boost::filesystem::path(p).parent_path().string()); }
	bool FilePath::exists() const{ return boost::filesystem::exists( p );}
	void FilePath::sanitise(){p=boost::filesystem::path(p).string();}
	bool FilePath::isDir() const{ return boost::filesystem::is_directory(p); }
	void FilePath::make(){ Lit::FileSystem::createDirectories(p); }
	
	FilePath& FilePath::operator = ( const FilePath& rk ){p=rk.p; return *this;}
	FilePath& FilePath::operator = ( const std::string& rk ){p=rk; return *this;}

	FilePath FilePath::operator + ( const FilePath& rk ) const{return FilePath(p+rk.p);}
	FilePath& FilePath::operator += ( const FilePath& rk ){p+=rk.p; return *this;}
	FilePath FilePath::operator + ( const std::string& rk ) const{return FilePath(p+rk);}
	FilePath& FilePath::operator += ( const std::string& rk ){p+=rk; return *this;}
	FilePath FilePath::operator + ( const char * str ) const{return FilePath(p+std::string(str));}
	FilePath& FilePath::operator += ( const char * str ){p+=std::string(str); return *this;}

};